﻿/*
Copyright © 2011 François Karman

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

See <license.txt> for the complete license of the software.
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;

namespace Simple.Storage.Serializer
{
    /// <summary>
    /// Implements a serializer that encapsulates other serializer and provides
    /// a chain-of-responsibility pattern for the serialization process.
    /// </summary>
    public class GroupedSerializer : AbstractSerializer, IGroupedSerializer
    {
        /// <summary>
        /// The encapsulated serializers.
        /// </summary>
        private ICollection<ISerializer> serializers;

        /// <summary>
        /// Initializes a new instance of the GroupedSerializer class.
        /// </summary>
        public GroupedSerializer()
        {
            this.serializers = new LinkedList<ISerializer>();
        }

        /// <summary>
        /// Retrieves a serializer for the specified type.
        /// </summary>
        /// <param name="type">The type to serialize.</param>
        /// <returns>The associated serializer; or <c>null</c>.</returns>
        public ISerializer Retrieve(Type type)
        {
            return this.serializers.FirstOrDefault(s => s.CanSerialize(type));
        }

        /// <summary>
        /// Adds a new serializer to the encapsulated groups.
        /// </summary>
        /// <param name="serializer">The serializer to be added.</param>
        public void Add(ISerializer serializer)
        {
            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }

            this.serializers.Add(serializer);
        }

        /// <summary>
        /// Removes all the serializers of the group.
        /// </summary>
        public void Clear()
        {
            this.serializers.Clear();
        }

        /// <summary>
        /// Implements the <see cref="ISerializer.CanSerialize"/> logic.
        /// </summary>
        /// <param name="type">
        /// The reference type - guaranty to be not <c>null</c>.
        /// </param>
        /// <returns>
        /// <c>true</c> if the serializer can work with instances of <paramref name="type"/>;
        /// <c>false</c> otherwise.
        /// </returns>
        protected override bool InternalCanSerialize(Type type)
        {
            return this.Retrieve(type) != null;
        }

        /// <summary>
        /// Implements the <see cref="ISerializer.CanWorkInPlace"/> logic.
        /// </summary>
        /// <param name="type">
        /// The reference type - guaranty to be not <c>null</c>.
        /// </param>
        /// <returns>
        /// <c>true</c> if the serializer can work with initialized instances of
        /// <paramref name="type"/>; <c>false</c> otherwise.
        /// </returns>
        protected override bool InternalCanWorkInPlace(Type type)
        {
            ISerializer s = this.Retrieve(type);
            return s != null && s.CanWorkInPlace(type);
        }

        /// <summary>
        /// Implements the serialization logic.
        /// </summary>
        /// <param name="writer">
        /// The writer - guaranty to be not <c>null</c>.
        /// </param>
        /// <param name="type">
        /// The reference type - guaranty to be not <c>null</c>.
        /// </param>
        /// <param name="value">
        /// The value to serialize - guaranty to be not <c>null</c> and associated with
        /// the current serializer.
        /// </param>
        protected override void InternalSerialize(BinaryWriter writer, Type type, object value)
        {
            ISerializer s = this.Retrieve(type);
            if (s == null)
            {
                string message = string.Format(Messages.Culture, Messages.SerializerUnknown, type.FullName);
                throw new SerializationException(message);
            }

            s.Serialize(writer, type, value);
        }

        /// <summary>
        /// Implements the deserialization logic.
        /// </summary>
        /// <param name="reader">
        /// The reader - guaranty to be not <c>null</c>.
        /// </param>
        /// <param name="type">
        /// The reference type - guaranty to be not <c>null</c>.
        /// </param>
        /// <returns>The deserialized value.</returns>
        protected override object InternalDeserialize(BinaryReader reader, Type type)
        {
            ISerializer s = this.Retrieve(type);
            if (s == null)
            {
                string message = string.Format(Messages.Culture, Messages.SerializerUnknown, type.FullName);
                throw new SerializationException(message);
            }

            return s.Deserialize(reader, type);
        }

        /// <summary>
        /// Implements the in-place deserialization logic.
        /// </summary>
        /// <param name="reader">
        /// The reader - guaranty to be not <c>null</c>.
        /// </param>
        /// <param name="type">
        /// The reference type - guaranty to be not <c>null</c>.
        /// </param>
        /// <param name="value">
        /// The container for the deserialized object - guaranty to be not <c>null</c>.
        /// </param>
        protected override void InternalDeserialize(BinaryReader reader, Type type, object value)
        {
            ISerializer s = this.Retrieve(type);
            if (s == null)
            {
                string message = string.Format(Messages.Culture, Messages.SerializerUnknown, type.FullName);
                throw new SerializationException(message);
            }

            s.Deserialize(reader, type, value);
        }
    }
}
